package com.birdboot.core;

import com.birdboot.controller.UserController;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

/**
 *
 * */
public class DispatcherServlet {
    //单例模式
    private static DispatcherServlet instance = new DispatcherServlet();
    private DispatcherServlet(){}
    public static DispatcherServlet getInstance(){ return instance; }

    private static File baseDir;
    private static File staticDir;
    static {
        try {
            baseDir = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(baseDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public void service(HttpServletRequest request, HttpServletResponse response){
        String path = request.getRequestURI();
        System.out.println("抽象路径"+path);
        //判断是否是业务
        if("/regUser".equals(path)){
            //处理用户注册
            UserController controller = new UserController();
            controller.reg(request,response);
        }else if("/loginUser".equals(path)){
            UserController controller = new UserController();
            controller.login(request,response);
        }else {
                File file = new File(staticDir,path);
                if(!file.isFile()){
                    file = new File(staticDir,"404.html");
                    response.setStatusCode(404);
                    response.setStatusReason("Not Found");
                    response.addHeader("Server","BirdServer");
                }else {
                    response.addHeader("Server","BirdServer");
                }
                response.setContentFile(file);
        }
    }
}
